<template>
	<el-dialog v-model="visible" fullscreen destroy-on-close @closed="$emit('closed')">
		<el-main class="page">
			<el-header style="padding: 0px">
				<div class="left-panel">
					<el-page-header :content="titleMap[mode]" @back="$emit('closed')"/>
				</div>
				<div class="right-panel">
					<el-button type="primary" icon="el-icon-finished" :loading="isSaveing" @click="submit()">保 存</el-button>
				</div>
			</el-header>
			<el-form :model="form" :rules="rules" :disabled="mode=='show'" ref="dialogForm" label-width="100px">
				<el-collapse v-model="activeNames" @change="handleChange" style="margin-top: 15px">
					<el-collapse-item title="接口配置" name="interface">
						<el-card shadow="never" style="margin-top: 10px">
							<el-row :gutter="20">
								<el-col :span="12">
									<el-form-item label="唯一编号" prop="name">
										<el-input v-model="form.name" placeholder="仅允许输入英文、下划线、数字" maxlength="50" onkeyup="this.value = this.value.replace(/[\u4e00-\u9fa5/\s+/]|[^a-zA-Z0-9\u4E00-\u9FA5]\[_]/g, '')" :disabled="mode=='edit'"/>
									</el-form-item>
									<el-form-item label="功能描述" prop="remark">
										<el-input v-model="form.remark" placeholder="接口的功能描述" maxlength="50" />
									</el-form-item>
								</el-col>
								<el-col :span="12">
									<el-form-item label="数据类型" prop="dataType">
										<jd-select v-model="form.dataType" dict="sys_api_type" dataType="String" clearable filterable style="width: 100%;" placeholder="请选择..."></jd-select>
									</el-form-item>
									<el-form-item label="数据对象" prop="databaseId" v-if="form.dataType=='sql'">
										<jd-select v-model="form.databaseId" :apiObj="$API.app.dbConn.getConnects" :apiProps="{label:'connName',value: 'connId'}" clearable style="width: 100%;" placeholder="请选择..."></jd-select>
									</el-form-item>
									<el-form-item label="数据格式" prop="responseType" v-if="form.dataType=='data'">
										<el-radio-group v-model="form.responseType">
											<el-radio label="json">JSON</el-radio>
											<el-radio label="text">TEXT</el-radio>
										</el-radio-group>
									</el-form-item>
									<el-form-item label="接口地址" prop="url" v-if="form.dataType=='api'">
										<el-input v-model="form.url" placeholder="" clearable></el-input>
									</el-form-item>
								</el-col>
							</el-row>
							<el-row v-if="form.dataType=='api'">
								<el-col :span="12">
									<el-form-item label="请求方式" prop="requestMethod">
										<el-radio-group v-model="form.requestMethod">
											<el-radio label="6">GET</el-radio>
											<el-radio label="7">POST</el-radio>
										</el-radio-group>
									</el-form-item>
								</el-col>
								<el-col :span="12" style="padding-left: 10px">
									<el-form-item label="传参方式" prop="paramType">
										<el-radio-group v-model="form.paramType">
											<el-radio label="json" :disabled="form.requestMethod == 6">JSON</el-radio>
											<el-radio label="form">FORM</el-radio>
										</el-radio-group>
									</el-form-item>
								</el-col>
							</el-row>
							<!--SQL数据库-->
							<el-row v-if="form.dataType=='sql'">
								<el-col :span="12">
									<el-form-item label="SQL语句" prop="query" style="padding-right: 10px">
										<jd-code-editor v-model="form.query" mode="sql"></jd-code-editor>
										<el-alert description="普通参数：name={name} or Date>{Date}；模糊匹配：name like {%name%}" type="warning" :closable="false" style="padding: 0px"/>
									</el-form-item>
								</el-col>
								<el-col :span="12">
									<el-form-item label="参数Params" prop="requestParams" style="padding-left: 10px">
										<jd-form-table v-model="requestParams" :addTemplate="addTemplate" :maxRow=5 placeholder="暂无参数">
											<el-table-column prop="val" label="参数名">
												<template #default="scope">
													<el-input v-model="scope.row.field" placeholder=""></el-input>
												</template>
											</el-table-column>
											<el-table-column prop="open" label="默认值">
												<template #default="scope">
													<el-input v-model="scope.row.defaultValue" placeholder=""></el-input>
												</template>
											</el-table-column>
										</jd-form-table>
										<div style="margin-top: 20px;">
											<el-button icon="jd-icon-sql" :loading="isSaveing" @click="parseSql()">测试接口</el-button>
											<el-button icon="jd-icon-static-data" :loading="isSaveing" @click="parseResponse()">自定义返回</el-button>
										</div>
									</el-form-item>
								</el-col>
							</el-row>
							<el-row>
								<el-col :span="24">
									<el-form-item label="静态数据" prop="query" v-if="form.dataType=='data'">
										<template v-if="form.responseType=='json'">
											<jd-code-editor v-model="form.query"></jd-code-editor>
											<el-alert description="建议统一用JSON的数据格式，带上code、msg、data字段，静态数据统一放入到data里面" type="warning" :closable="false" style="padding: 0px"/>
										</template>
										<template v-else>
											<el-input v-model="form.query" type="textarea" :autosize="{ minRows: 10, maxRows: 20 }" />
										</template>
									</el-form-item>
									<template v-if="form.dataType=='api'">
										<el-row>
											<el-col :span="24">
												<el-form-item label="Header" prop="requestHeaders">
													<jd-form-table v-model="requestHeaders" :addTemplate="addTemplate" :maxRow=5 placeholder="暂无Header请求头">
														<el-table-column prop="val" label="键名" width="300">
															<template #default="scope">
																<el-input v-model="scope.row.field" placeholder=""></el-input>
															</template>
														</el-table-column>
														<el-table-column prop="open" label="键值">
															<template #default="scope">
																<el-input v-model="scope.row.defaultValue" placeholder=""></el-input>
															</template>
														</el-table-column>
													</jd-form-table>
												</el-form-item>
											</el-col>
										</el-row>
										<el-row>
											<el-col :span="12">
												<el-form-item label="Params" prop="requestParams">
													<jd-form-table v-model="requestParams" :addTemplate="addTemplate" :maxRow=5 placeholder="暂无参数">
														<el-table-column prop="val" label="参数名">
															<template #default="scope">
																<el-input v-model="scope.row.field" placeholder=""></el-input>
															</template>
														</el-table-column>
														<el-table-column prop="open" label="默认值">
															<template #default="scope">
																<el-input v-model="scope.row.defaultValue" placeholder=""></el-input>
															</template>
														</el-table-column>
													</jd-form-table>
												</el-form-item>
											</el-col>
											<el-col :span="12">
												<el-form-item label="" style="padding-left: 10px">
													<div style="margin-top: 20px;">
														<el-button icon="el-icon-switch" :loading="isSaveing" @click="parseApi()">测试接口</el-button>
														<el-button icon="jd-icon-static-data" :loading="isSaveing" @click="parseResponse()">自定义返回</el-button>
													</div>
												</el-form-item>
											</el-col>
										</el-row>
									</template>
								</el-col>
							</el-row>
						</el-card>
					</el-collapse-item>
				</el-collapse>
				<el-form name="parseData"  v-if="form.dataType!='data' && isTesting">
					<el-form-item label="解析结果">
						<jd-code-editor ref="editor" v-model="responseData" mode="javascript" theme="dracula" :options="{styleActiveLine: false}"></jd-code-editor>
					</el-form-item>
				</el-form>
				<el-row>
					<el-col :span="24" style="padding-left: 120px;padding-top:30px;">
						<el-button type="primary" icon="el-icon-finished" :loading="isSaveing" @click="submit()">保  存</el-button>
					</el-col>
				</el-row>
			</el-form>
		</el-main>
		<jd-dialog v-model="jsVisible" draggable title="数据处理">
			<el-row>
				<el-col :span="24">
					<jd-code-editor v-model="form.processing" mode="javascript" theme="darcula" :options="{lineNumbers: false}" ref="editor"></jd-code-editor>
				</el-col>
			</el-row>
			<template #footer>
				<el-button @click="jsVisible = false">取 消</el-button>
				<el-button type="primary" @click="saveParseData">确 定</el-button>
			</template>
		</jd-dialog>
	</el-dialog>
</template>

<script>
	import { defineAsyncComponent } from 'vue';
	const jdCodeEditor = defineAsyncComponent(() => import('@/components/jdCodeEditor'));

	export default {
		components: {
			jdCodeEditor,
		},
		emits: ['success', 'closed'],
		props: {
			interfaceId: { type: Number, default: 0 },
			group:null,
		},
		data() {
			return {
				mode: "add",
				titleMap: {
					add: '新增接口',
					edit: '编辑接口',
					show: '查看'
				},
				visible: false,
				jsVisible: false,
				isSaveing: false,
				isTesting: false,
				addTemplate: {
					field: '',
					defaultValue: ''
				},
				//表单数据
				form: {
					id: null,
					type: this.group==null?"default":this.group,
					name: null,
					url: null,
					requestMethod: 6,
					responseType: "json",
					query: null,
					requestParams: [],
					ip: null,
					databaseId: 1,
					dataType: "data",
					checkType: 0,
					requestHeaders: [],
					processing: this.defParseData,
					remark: null,
					paramType: "form",
				},
				requestHeaders: [],
      			requestParams: [],
				responseData: [],
				processing: this.defParseData,
				//验证规则
				rules: {
					name:[
						{required: true, message: '请输入唯一编号'}
					],
					remark:[
						{required: true, message: '请输入功能说明'}
					],
					dataType:[
						{required: true, message: '请选择数据类型'}
					],
				},
				activeNames: "interface",
				defParseData:
`(data) =>
{
	// 处理数据逻辑
	// 返回所需的数据
	return data
}`,
				defSql: 'select * from users',
				// 默认静态数据格式
				defJson:
`{
	code: 200,
	msg: '操作成功',
	data: [
		{
			"name": "JPortal",
			"desc": "基于低代码引擎构建的数字门户系统"
		},
		{
			"name": "...",
			"desc": "..."
		}
		// 按JSON的数据格式输出
	]
}`
			}
		},
		watch:{
			'form.dataType'(val){
				this.setQuery(val);
			},
			'form.requestMethod'(val){
				if (val==6){
					this.form.paramType = "form";
				}
			},
			'interfaceId'(){
				this.loadInterface();
			}
		},
		mounted() {
			this.loadInterface();
		},
		methods: {
			//显示
			open(mode='add'){
				this.mode = mode;
				this.visible = true;
				this.requestParams = [];
				return this
			},
			// 获取接口信息
			async loadInterface(){
				if (this.interfaceId == 0){
					this.form.query = this.defJson;
					return;
				}

				var res = await this.$API.app.interface.get.get(this.interfaceId);
				if (res.code == 200){
					Object.assign(this.form, res.data);

					if (res.data.requestHeaders!=null){
						this.requestHeaders = JSON.parse(res.data.requestHeaders);
					}
					if (res.data.requestParams!=null){
						this.requestParams = JSON.parse(res.data.requestParams);
					}
					this.processing = res.data.processing;
				}
			},
			// 设置查询值
			setQuery(dataType){
				if (dataType == 'sql'){
					this.form.query = this.form.query == null ? this.defSql : this.form.query;
				} else if (dataType == 'data'){
					this.form.query = this.form.query == null ? this.defJson : this.form.query;
					this.form.url = "";
					this.form.databaseId = null;
				} else if (dataType == 'api'){
					this.form.requestMethod = "6";
				}
			},
			handleChange(val){
				this.activeNames = val;
			},
			// 解析SQL语句
			async parseSql() {
				this.isTesting = true;
				let param = {
					data:this.form,
					paramList:this.requestParams
				}
				let res = await this.$API.app.interface.testInterface.post(param);
				if (res.code == 200){
					this.responseData = JSON.stringify(res.data, null, 4);
				}else {
					this.$message.error(res.msg)
				}
			},
			// 解析API接口
			async parseApi() {
				this.isTesting = true;
				let param = {
					data: this.form,
					paramList: this.requestParams
				}
				let res = await this.$API.app.interface.testInterface.post(param);
				if (res.code == 200) {
					this.responseData = JSON.stringify(res.data, null, 4);
				} else {
					this.$message.error(res.msg)
				}
			},
			// 接口数据处理
			parseResponse(){
				this.jsVisible = true;
				var jsCode = this.processing==null? this.defParseData: this.processing;
				this.$nextTick(() => {
					this.$refs.editor.coder.setValue(jsCode);
				});
			},
			saveParseData(){
				this.processing = this.$refs.editor.coder.getValue;
				this.jsVisible = false;
			},
			//表单提交方法
			submit(){
				this.$refs.dialogForm.validate(async (valid) => {
					if (valid) {
						this.isSaveing = true;

						if (this.requestHeaders!=null){
							this.form.requestHeaders = JSON.stringify(this.requestHeaders);
						}
						if (this.requestParams!=null){
							this.form.requestParams = JSON.stringify(this.requestParams);
						}

						// 保存时清除无用的字段值
						if (this.form.dataType == "sql"){
							this.form.requestMethod = 3;
							this.form.requestHeaders = JSON.stringify([]);
							// SQL语句
						} else if (this.form.dataType == "data"){
							// 静态数据
							this.form.url = null;
							this.form.requestMethod = 6;
							this.form.requestParams = JSON.stringify([]);
							this.form.databaseId = null;
							this.form.requestHeaders = null;
							this.form.processing = null;

						} else if (this.form.dataType == "api"){
							// API接口
							this.form.query = "";
							this.form.databaseId = "";
						}

						var res = {}
						if (this.mode == 'add'){
							res = await this.$API.app.interface.add.post(this.form);
						} else {
							res = await this.$API.app.interface.update.put(this.form);
						}
						if(res.code == 200){
							this.$emit('success', this.form, this.mode)
							this.visible = false;
							this.$message.success("操作成功")
						}else{
							this.$alert(res.msg, "提示", {type: 'error'})
						}
						this.isSaveing = false;
					}

				})
			},
		}
	}
</script>

<style>
.el-collapse-item__header{
	font-weight: bolder;
	font-size: 16px;
	margin-top: 10px;
}
</style>
